package org.zoomdev.zoom.aop.factory;

import javassist.ClassPool;
import org.apache.commons.lang3.StringUtils;
import org.zoomdev.zoom.aop.Invoker;
import org.zoomdev.zoom.common.utils.Utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MethodInvokerFactory extends SingleMethodFactory<Invoker, Method> {

    public static MethodInvokerFactory FACTORY = new MethodInvokerFactory();

    public MethodInvokerFactory() {
        super();
    }

    public MethodInvokerFactory(ClassPool classPool) {
        super(classPool);
    }

    @Override
    protected String getClassName(Method param) {
        return param.getDeclaringClass().getName() + "." + param.getName() + "$Invoker";
    }

    private String getValue(Class type) {
        return type.getSimpleName();
    }


    @Override
    public Invoker create(Method method) {
        return super.create(method);
    }

    private String getReturnType(Class type) {
        if (type == Void.class || type == void.class) {
            return "";
        }

        if (type.isPrimitive()) {
            return "return ($w)";
        }

        return "return ";
    }


    protected String createBody(Method method) {
        Class type = method.getDeclaringClass();
        Class[] types = method.getParameterTypes();
        List<String> cast = new ArrayList<>();
        for (int i = 0; i < types.length; ++i) {
            if (types[i].isPrimitive()) {
                Class wrapType = Utils.getWrapClass(types[i]);
                String ct = String.format("((%s)$2[%d]).%sValue()", wrapType.getName(), i, getValue(types[i]));
                cast.add(ct);
            } else if (types[i].isArray()) {
                cast.add(String.format("(%s)$2[%d]", types[i].getComponentType().getName() + "[]", i));
            } else {
                cast.add(String.format("(%s)$2[%d]", types[i].getName(), i));
            }
        }

        Class returnType = method.getReturnType();

        String str = String.format("%s((%s)$1).%s(%s);",
                getReturnType(returnType),
                type.getName(), method.getName(),
                StringUtils.join(cast, ","));
        if (returnType == Void.class || returnType == void.class) {
            str += "return null;";
        }
        return str;
    }
}
